import network import time from machine import Pin import dht import socket import json # DHT11 sensor setup try: sensor = dht.DHT11(Pin(18)) # Try GPIO 4 first (change if your sensor is on a different pin) print("DHT11 initialized on GPIO 4") except Exception as e: print("DHT11 initialization error:", e) sensor = None # WiFi connection wlan = network.WLAN(network.STA_IF) wlan.active(False) time.sleep(1) wlan.active(True) print("Scanning for networks...") networks = wlan.scan() for net in networks: print(" ", net[0].decode()) print("\nAttempting connection...") wlan.connect("YOUR_SSID", "YOUR_PASSWORD") # Wait for connection with detailed status max_wait = 20 while max_wait > 0: status = wlan.status() print(f'Connection status: {status}') if status == 1000 or status == 3: # Connected break if status < 0: # Error break max_wait -= 1 print('waiting for connection...') time.sleep(1) # Status codes: 1000=CONNECTED (ESP32), 3=CONNECTED (ESP8266) status = wlan.status() print(f'Final status: {status}') if status == 1000 or status == 3: # Successfully connected print('✓ Connected successfully!') config = wlan.ifconfig() print('IP address:', config[0]) print('Subnet mask:', config[1]) print('Gateway:', config[2]) print('DNS:', config[3]) else: if status == 1: print('ERROR: Wrong password') elif status == 2: print('ERROR: Network not found') elif status == 0: print('ERROR: Timeout - still connecting') else: print(f'ERROR: Connection failed with status {status}') raise RuntimeError('network connection failed') # Set up web server addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Allow reuse of address s.bind(addr) s.listen(1) print('listening on', addr) # Your sensor location (latitude, longitude) SENSOR_LAT = 53.5461 # Edmonton example SENSOR_LON = -113.4938 def read_sensor(): if sensor is None: print("Sensor not initialized") return None, None try: time.sleep(2) # DHT11 needs 2 seconds between reads sensor.measure() temp = sensor.temperature() humidity = sensor.humidity() print(f"Sensor read: {temp}°C, {humidity}%") return temp, humidity except OSError as e: print(f"Sensor read error: {e}") return None, None except Exception as e: print(f"Unexpected error: {e}") return None, None while True: try: cl, addr = s.accept() print('client connected from', addr) request = cl.recv(1024) request = str(request) # Read sensor data temp, humidity = read_sensor() # Create JSON response data = { "temperature": temp, "humidity": humidity, "latitude": SENSOR_LAT, "longitude": SENSOR_LON, "timestamp": time.time() } response = json.dumps(data) # Send CORS headers to allow cross-origin requests cl.send('HTTP/1.0 200 OK\r\n') cl.send('Content-Type: application/json\r\n') cl.send('Access-Control-Allow-Origin: *\r\n') cl.send('\r\n') cl.send(response) cl.close() except OSError as e: cl.close() print('connection closed')